package com.hpf.community.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hpf.community.annotations.MonitorLog;
import com.hpf.community.constants.CommunityConstants;
import com.hpf.community.enums.LogEnum;
import com.hpf.community.model.CommunityModel;
import com.hpf.community.model.RoleAuthModel;
import com.hpf.community.model.UserModel;
import com.hpf.community.service.ICommunityService;
import com.hpf.community.service.IRoleAuthService;
import com.hpf.community.service.IUserService;
import com.hpf.community.shiro.PasswordHelper;
import com.hpf.community.utils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 *　　
 *   User 控制器    用户表
 *
 *   @author huangpengfei
 *   @since 2020-04-04
 */

@RestController
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public IUserService userService;

//    @Autowired
    public PasswordHelper passwordHelper;

    @Autowired
    public IRoleAuthService roleAuthService;

    @Autowired
    public ICommunityService communityService;

    @Autowired
    public SpringHelperUtils springHelperUtils;

    /**
     * 查询社团成员
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/user")
    public StandardResult selectPage(@ModelAttribute UserModel userModel, @RequestParam(value = "isSingle")Boolean isSingle, @RequestParam(value = "pageSize",required = false)Integer pageSize,@RequestParam(value = "pageNumber",required = false) Integer pageNumber,@RequestParam(value = "searchKey",required = false)String searchKey) {
		try {
			if (pageSize == null || pageNumber == null) {
				return StandardResult.faildCheck("缺少必要的分页参数！");
			}
	     	Page<UserModel> page = new Page<UserModel>(pageNumber, pageSize);
	     	Wrapper<UserModel> wrapper = new EntityWrapper<UserModel>();
	     	if(StringUtils.isNotBlank(searchKey)){
	     	    wrapper.like(UserModel.NAME,searchKey);
	     	    wrapper.or();
                wrapper.like(UserModel.HOBBY,searchKey);
                wrapper.or();
                wrapper.like(UserModel.CLASS_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.COM_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.TELEPHONE,searchKey);
                wrapper.or();
                wrapper.like(UserModel.EMAIL,searchKey);
	     	}
            if(StringUtils.isNotBlank(userModel.getStatus())){
                wrapper.andNew();
                wrapper.eq(UserModel.STATUS,userModel.getStatus());
            }
            if(StringUtils.isNotBlank(userModel.getSex())){
                wrapper.andNew();
                wrapper.eq(UserModel.SEX,userModel.getSex());
            }
            if(StringUtils.isNotBlank(userModel.getComId())){
                wrapper.andNew();
                wrapper.eq(UserModel.COM_ID,userModel.getComId());
            }
            if(StringUtils.isNotBlank(userModel.getClassId())){
                wrapper.andNew();
                wrapper.eq(UserModel.CLASS_ID,userModel.getClassId());
            }
	     	wrapper.andNew();
	     	if(isSingle){
	     	    //如果是普通成员查询
                wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_PTCH);//查询社团成员
                if(!StringUtils.equals(CommonUtils.getCurrentUserName(),CommunityConstants.ADMIN)){
                    //如果不是管理员，只能查看自己社团的成员
                    wrapper.eq(UserModel.COM_ID,CommonUtils.getCurrentUserComId());
                }
	     	}else {
	     	    //后台用户查询
                wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_HTYH);//查询后台成员
                wrapper.or();
                wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_GLY);
            }
            wrapper.andNew();
            wrapper.eq(UserModel.IS_DELETE, CommunityConstants.USER_STATUS_ZC);
	     	userService.selectPage(page, wrapper);
			return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return PaginationResult.faild(e);
		}
    }


    /**
     * 查询社团管理员和后台用户
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/userBack")
    @RequiresRoles("3")
    public StandardResult selectPageBack(@ModelAttribute UserModel userModel, @RequestParam(value = "pageSize",required = false)Integer pageSize,@RequestParam(value = "pageNumber",required = false) Integer pageNumber,@RequestParam(value = "searchKey",required = false)String searchKey) {
        try {
            if (pageSize == null || pageNumber == null) {
                return StandardResult.faildCheck("缺少必要的分页参数！");
            }
            Page<UserModel> page = new Page<UserModel>(pageNumber, pageSize);
            Wrapper<UserModel> wrapper = new EntityWrapper<UserModel>();
            if(StringUtils.isNotBlank(searchKey)){
                wrapper.like(UserModel.NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.HOBBY,searchKey);
                wrapper.or();
                wrapper.like(UserModel.CLASS_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.COM_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.TELEPHONE,searchKey);
                wrapper.or();
                wrapper.like(UserModel.EMAIL,searchKey);
            }
            if(StringUtils.isNotBlank(userModel.getStatus())){
                wrapper.andNew();
                wrapper.eq(UserModel.STATUS,userModel.getStatus());
            }
            if(StringUtils.isNotBlank(userModel.getSex())){
                wrapper.andNew();
                wrapper.eq(UserModel.SEX,userModel.getSex());
            }
            if(StringUtils.isNotBlank(userModel.getComId())){
                wrapper.andNew();
                wrapper.eq(UserModel.COM_ID,userModel.getComId());
            }
            if(StringUtils.isNotBlank(userModel.getClassId())){
                wrapper.andNew();
                wrapper.eq(UserModel.CLASS_ID,userModel.getClassId());
            }
            wrapper.andNew();
            //后台用户查询
            wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_HTYH);//查询后台成员
            wrapper.or();
            wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_GLY);
            wrapper.andNew();
            wrapper.eq(UserModel.IS_DELETE, CommunityConstants.USER_STATUS_ZC);
            userService.selectPage(page, wrapper);
            return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return PaginationResult.faild(e);
        }
    }


    /**
     * 查询社团成员
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/userCheck")
    @RequiresRoles("3")
    public StandardResult selectPageCheck(@ModelAttribute UserModel userModel,@RequestParam(value = "pageSize",required = false)Integer pageSize,
                                          @RequestParam(value = "pageNumber",required = false) Integer pageNumber,
                                          @RequestParam(value = "searchKey",required = false)String searchKey
                                          ) {
        try {
            if (pageSize == null || pageNumber == null) {
                return StandardResult.faildCheck("缺少必要的分页参数！");
            }
            Page<UserModel> page = new Page<UserModel>(pageNumber, pageSize);
            Wrapper<UserModel> wrapper = new EntityWrapper<UserModel>();
            if(StringUtils.isNotBlank(searchKey)){
                wrapper.like(UserModel.NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.HOBBY,searchKey);
                wrapper.or();
                wrapper.like(UserModel.CLASS_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.COM_NAME,searchKey);
                wrapper.or();
                wrapper.like(UserModel.TELEPHONE,searchKey);
                wrapper.or();
                wrapper.like(UserModel.EMAIL,searchKey);
            }
            if(StringUtils.isNotBlank(userModel.getStatus())){
                wrapper.andNew();
                wrapper.eq(UserModel.STATUS,userModel.getStatus());
            }
            if(StringUtils.isNotBlank(userModel.getSex())){
                wrapper.andNew();
                wrapper.eq(UserModel.SEX,userModel.getSex());
            }
            if(StringUtils.isNotBlank(userModel.getComId())){
                wrapper.andNew();
                wrapper.eq(UserModel.COM_ID,userModel.getComId());
            }
            if(StringUtils.isNotBlank(userModel.getClassId())){
                wrapper.andNew();
                wrapper.eq(UserModel.CLASS_ID,userModel.getClassId());
            }
            wrapper.andNew();
            wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_PTCH);//查询社团成员
            //后台用户查询
            wrapper.ne(UserModel.ROLE,CommunityConstants.USER_ROLE_HTYH);
            wrapper.eq(UserModel.STATUS,CommunityConstants.MEMBER_CHECK_DSH);
            wrapper.eq(UserModel.IS_DELETE, CommunityConstants.USER_STATUS_ZC);
            //只能角色3也就是管理员才能查看审批数据
            if(CommonUtils.getCurrentUser().getRole().equals(CommunityConstants.USER_ROLE_GLY)){
                userService.selectPage(page, wrapper);
                return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
            }else {
                return StandardResult.ok();
            }
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return PaginationResult.faild(e);
        }
    }


	/**
     * 获取列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/userList")
    public StandardResult selectList(@ModelAttribute UserModel userModel) {
		try {
			Wrapper<UserModel> wrapper = new EntityWrapper<UserModel>(userModel);
			return StandardResult.ok(null, userService.selectList(wrapper));
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return StandardResult.faild(e);
		}
    }

     /**
      * 添加
      *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PostMapping("/user")
    @MonitorLog(value = "添加社员、修改社员信息或者审核社员，具体看详细日志",operateType = LogEnum.INSERT)
    public StandardResult insert(@ModelAttribute UserModel userModel) {
		try {
            if(StringUtils.isNotBlank(userModel.getPass())){
                passwordHelper.encryptPassword(userModel);
            }
            if(StringUtils.isBlank(userModel.getId())){
                if(StringUtils.isNotBlank(userModel.getName())){
                    String name = userModel.getName();
                    Wrapper<UserModel> wrapper = new EntityWrapper<>();
                    wrapper.eq(UserModel.NAME,name);
                    int count = userService.selectCount(wrapper);
                    if(count > 0){
                        return StandardResult.faild("该用户名已存在，请确认用户名是否正确");
                    }
                }
                userModel.setId(CommonUtils.getUUID());
                userModel.setCreateDatetime(new Date());
                userModel.setCreateUserId(CommonUtils.getCurrentUserId());
		    }else {
		        userModel.setModifyDatetime(new Date());
		        userModel.setModifyUserId(CommonUtils.getCurrentUserId());
            }
            userService.insertOrUpdate(userModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 添加后台用户
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PostMapping("/userBack")
    @RequiresRoles("3")
    @MonitorLog(value = "添加或者修改后台用户，具体看详细日志",operateType = LogEnum.INSERT)
    public StandardResult insertBack(@ModelAttribute UserModel userModel) {
        try {
            if(StringUtils.isNotBlank(userModel.getPass())){
                passwordHelper.encryptPassword(userModel);
            }
            if(StringUtils.isBlank(userModel.getId())){
                if(StringUtils.isNotBlank(userModel.getName())){
                    String name = userModel.getName();
                    Wrapper<UserModel> wrapper = new EntityWrapper<>();
                    wrapper.eq(UserModel.NAME,name);
                    int count = userService.selectCount(wrapper);
                    if(count > 0){
                        return StandardResult.faild("该用户名已存在，请确认用户名是否正确");
                    }
                }
                userModel.setId(CommonUtils.getUUID());
                userModel.setCreateDatetime(new Date());
                userModel.setCreateUserId(CommonUtils.getCurrentUserId());
            }else {
                if(StringUtils.isNotBlank(userModel.getStatus())){
                    if(StringUtils.equals(userModel.getStatus(),CommunityConstants.USER_STATUS_ZC)){
                        //启用需要判断该账号所属的社团是否被禁用
                        UserModel model = userService.selectById(userModel.getId());
                        CommunityModel communityModel = communityService.selectById(model.getComId());
                        if(StringUtils.equals(communityModel.getStatus(),CommunityConstants.USER_STATUS_JY)){
                            return StandardResult.faild("您启用的账户所属社团已被禁用，请联系相关人员");
                        }
                    }
                }
                userModel.setModifyDatetime(new Date());
                userModel.setModifyUserId(CommonUtils.getCurrentUserId());
            }
            userService.insertOrUpdate(userModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }


    /**
     * 移出社团
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PutMapping("/user")
    @MonitorLog(value = "移出社员",operateType = LogEnum.UPDATE)
    public StandardResult updateById(@RequestBody UserModel userModel) {
        try {
            userModel.setIsDelete(CommunityConstants.USER_STATUS_JY);
            userModel.setModifyUserId(CommonUtils.getCurrentUserId());
            userModel.setModifyDatetime(new Date());
            userService.updateById(userModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
        * 通过id获取详情
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/user/{id}")
    public StandardResult selectById(@PathVariable String id) {
		try {
		     return StandardResult.ok(userService.selectById(id));
		} catch (Exception e) {
		     logger.error("异常信息:", e);
		     return StandardResult.faild(e);
		}
    }

    /**
     * 通过id删除数据
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @DeleteMapping("/user/{id}")
    public StandardResult deleteById(@PathVariable String id) {
        try {
            userService.deleteById(id);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 获取当前登录用户的信息
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/userInfo")
    public StandardResult selectUserInfo() {
        try {
            return StandardResult.ok(userService.selectById(CommonUtils.getCurrentUserId()));
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 获取当前登录用户的信息
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/userAuthList")
    public StandardResult getAuthList(){
        try {
            //对返回的数据做处理
            List<RoleAuthModel> roleAuthModels = roleAuthService.selectRoleAuthList(CommonUtils.getCurrentUser().getRole());

            List<RoleAuthModel> parentList = new ArrayList<>();
            List<RoleAuthModel> sonList = new ArrayList<>();
            //剥离父菜单和子菜单
            for(RoleAuthModel roleAuthModel:roleAuthModels){
                if(StringUtils.isBlank(roleAuthModel.getParentId())){
                    //父菜单
                    parentList.add(roleAuthModel);
                }else {
                    sonList.add(roleAuthModel);
                }
            }
            //匹配父子菜单
            List<List<RoleAuthModel>> arrayList = new ArrayList<>();
            for(RoleAuthModel parent:parentList){
                List<RoleAuthModel> sons = new ArrayList<>();
                sons.add(parent);
                for(RoleAuthModel son:sonList){
                    if(StringUtils.equals(son.getParentId(),parent.getAuthId())){
                        sons.add(son);
                    }
                }
                arrayList.add(sons);
            }
            return StandardResult.ok(arrayList);
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }


    /**
     * 头像上传
     * @param: [file]
     * @return: com.hpf.community.utils.StandardResult
     * @author: HPF
     * @date: 2020/4/21 16:28
     */
    @PostMapping("/imageUpload")
    public StandardResult imageUpload(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传的文件
        MultipartFile file = multipartRequest.getFile("file");
        String result_msg="";//上传结果信息
        Map<String,Object> root=new HashMap<String, Object>();
        if (file.getSize() / 1000 > 1000){
            result_msg="图片大小不能超过1000KB";
        } else{
            //判断上传文件格式
            String fileType = file.getContentType();
            if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
                final String localPath= springHelperUtils.getHeadPath();
                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                //重新生成文件名
                fileName = CommonUtils.getUUID()+suffixName;
                if (FileUtils.upload(file, localPath, fileName)) {
                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
                    String relativePath="img/headImg/"+fileName;
                    root.put("relativePath",relativePath);
                    //存入数据库
                    UserModel userModel = userService.selectById(CommonUtils.getCurrentUserId());
                    logger.info(userModel.getHeadImg()+"1---------------->");
                    if(StringUtils.isNotBlank(userModel.getHeadImg())){
                        //更新之前把之前的图片删除
                        FileUtil.del(springHelperUtils.getDelPath()+userModel.getHeadImg());
                    }
                    logger.info(userModel.getHeadImg()+"2---------------->");
                    userModel.setHeadImg(relativePath);
                    userService.updateById(userModel);
                    result_msg="图片上传成功";
                }
                else{
                    result_msg="图片上传失败";
                }
            }
            else{
                result_msg="图片格式不正确";
            }
        }
        root.put("result_msg",result_msg);
        return StandardResult.ok(root);
    }
}
